import React, { useMemo } from 'react';
import Event from '@y.dsh/event';
import usePassiveSupported from '@y.dsh/hooks/lib/usePassiveSupported';
import { findParentNode } from '@y.dsh/utils/lib/dom';
import longPressButton from './sideEvent';
import { SideButtonProps } from './';

function SideButton(props: SideButtonProps): JSX.Element {
  // 删除不属于button的属性
  const buttonProps = {
    ...props,
    onTap: undefined,
    childrenNotAllowDown: undefined,
    inlayType: undefined,
    index: undefined
  };
  delete buttonProps.onTap;
  delete buttonProps.childrenNotAllowDown;
  delete buttonProps.inlayType;
  delete buttonProps.index;

  const passiveSupported = usePassiveSupported(); // 检测是否支持{ passive: false }
  const eventOptions = useMemo(() => passiveSupported ? { passive: false } : false, [passiveSupported]);

  return (
    <Event
      longPressPreventDefault
      onLongPress={(event) => {
        longPressButton(event, props.childrenNotAllowDown, eventOptions);
      }}
      onTap={(event) => {
        const button = findParentNode(event.target as HTMLElement, 'easy-scroll-side-button-drag'); // 判断当前元素是不是抖动状态
        if (!button) {
          // 非抖动状态才可以触发onTap
          if (props.onTap) {
            props.onTap();
          }
        }
      }}
    >
      <button
        className="easy-scroll-side-button"
        {...buttonProps}
      />
    </Event>
  )
}

export default SideButton
